package com.zhang.first.day04;

import com.zhang.first.utils.IntegerSource;
import org.apache.commons.lang3.text.StrBuilder;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;

/**
 * ListState举例
 * 每来一条数据，将历史数据进行排序输出
 *
 * @title:
 * @author: zhang
 * @date: 2022/1/17 18:19
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntegerSource())
                .keyBy(r -> 1)
                .process(new SortHistory())
                .print();

        env.execute();
    }

    public static class SortHistory extends KeyedProcessFunction<Integer,Integer,String>{
        private ListState<Integer> historyData;

        @Override
        public void open(Configuration parameters) throws Exception {
            historyData = getRuntimeContext().getListState(new ListStateDescriptor<Integer>(
                    "history-data",Types.INT
            ));

        }

        @Override
        public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, String>.Context ctx, Collector<String> out) throws Exception {
            historyData.add(value);
            ArrayList<Integer> integers = new ArrayList<>();
            for (Integer i : historyData.get()) {
                integers.add(i);
            }
            integers.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1-o2;
                }
            });
            StrBuilder sb = new StrBuilder();
            for (int i = 0; i < integers.size() - 1; i++) {
                sb.append(integers.get(i) + "->");
            }
            sb.append(integers.get(integers.size()-1));
            out.collect(sb.toString());
        }

    }
}
